#include<iostream>
#include<string>

using namespace std;

class Solution {
public:
    int myAtoi(string str) {
        int sign = 1;
        int result = 0; 
        int i = 0;

        while (i < str.size() && str[i] == ' ')
        {
            i++;
        }

        if (i < str.size() && (str[i] == '+' || str[i] == '-'))
        {
            sign = (str[i] == '-') ? -1 : 1;
            i++;
        }

        while (i < str.size() && str[i] <= '9' && str[i] >= '0')
        {
            int digit = str[i] - '0';

            if (result > (INT_MAX - digit) / 10)
            {
                return (sign == -1) ? INT_MIN : INT_MAX;
            }

            result = result * 10 + digit;
            i++;
        }

        return result * sign;
    }
};